var YUEOE_bpmnModeler;//流程图形实例化对象
var YUEOE_NewProcess;//创建一个流程图方法
var YUEOE_InitProcessPage;//初始化流程页面方法
var YUEOE_require,YUEOE_module,YUEOE_exports;

/**
 * 使用文本域替换原有的可编辑DIV。因为可编辑DIV在chrome浏览器中失效
 * @constructor
 */
var YUEOE_TextAreaExchange = function ($) {
    $("#js-drop-zone").click(function () {
        modifyDiv();
    });
    function modifyDiv() {
        $("div[contenteditable=true]").each(function (index, el) {
            if (!el.exTextArea) {
                $(el).click(function () {
                    var el = this;
                    var childdiv;
                    if (!el.exTextArea) {
                        var parent = el.parentNode;
                        var childdiv = $('<textarea></textarea>');//创建一个子div
                        childdiv.attr('id', '_' + el.id); //给子div设置id
                        childdiv.attr('name', el.name); //给子div设置id
                        childdiv.val(el.innerText);
                        $(el).hide();
                        parent.appendChild(childdiv[0]);
                        el.exTextArea = childdiv[0];
                        childdiv.change(function () {
                            $('#' + this.id.substr(1))[0].innerText = this.value;
                        });
                        childdiv.blur(function () {
                            $('#' + this.id.substr(1)).show();
                            $(this).hide();
                        })
                        childdiv.focus(function () {
                            $('#' + this.id.substr(1)).hide();
                        })
                    } else {
                        childdiv = $(el.exTextArea);
                        childdiv.show();
                    }
                    childdiv.focus();
                })
            }
        });
    }
    setTimeout(function () {
        modifyDiv();
    }, 50)
}

var YUEOE_drawMapLogic = function(require,module,exports,_prelude,arrs,option1,option2,isRun){
    YUEOE_require = require;
    YUEOE_module = module;
    YUEOE_exports = exports;
    if(!isRun){
        return;
    }
    'use strict';

    var _jquery = require('jquery');

    var _jquery2 = _interopRequireDefault(_jquery);

    var _Modeler = require('bpmn-js/lib/Modeler');

    var _Modeler2 = _interopRequireDefault(_Modeler);

    var _bpmnJsPropertiesPanel = require('bpmn-js-properties-panel');

    var _bpmnJsPropertiesPanel2 = _interopRequireDefault(_bpmnJsPropertiesPanel);

    var _camunda = require('bpmn-js-properties-panel/lib/provider/camunda');

    var _camunda2 = _interopRequireDefault(_camunda);

    var _camunda3 = require('camunda-bpmn-moddle/resources/camunda');

    var _camunda4 = _interopRequireDefault(_camunda3);

    var _minDash = require('min-dash');

    var _newDiagram = require('../resources/newDiagram.bpmn');

    var _newDiagram2 = _interopRequireDefault(_newDiagram);

    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

    var container = (0, _jquery2.default)('#js-drop-zone');

    var canvas = (0, _jquery2.default)('#js-canvas');

    var bpmnModeler = new _Modeler2.default({
        container: canvas,
        propertiesPanel: {
            parent: '#js-properties-panel'
        },
        additionalModules: [_bpmnJsPropertiesPanel2.default, _camunda2.default],
        moddleExtensions: {
            camunda: _camunda4.default
        }
    });
    YUEOE_bpmnModeler = bpmnModeler;
    container.removeClass('with-diagram');
    //隐藏水印图标
    (0, _jquery2.default)('.bjs-powered-by').hide();

    YUEOE_NewProcess = function createNewDiagram() {
        YUEOE_TextAreaExchange((0, _jquery2.default));
        return openDiagram(_newDiagram2.default);
    }

    function openDiagram(xml) {

        bpmnModeler.importXML(xml, function (err) {
            if (err) {
                container.removeClass('with-diagram').addClass('with-error');

                container.find('.error pre').text(err.message);

                console.error(err);
            } else {
                container.removeClass('with-error').addClass('with-diagram');
            }
        });
        return bpmnModeler;
    }

    function saveSVG(done) {
        bpmnModeler.saveSVG(done);
    }

    function saveDiagram(done) {

        bpmnModeler.saveXML({ format: true }, function (err, xml) {
            done(err, xml);
        });
    }

    function registerFileDrop(container, callback) {

        function handleFileSelect(e) {
            e.stopPropagation();
            e.preventDefault();

            var files = e.dataTransfer.files;

            var file = files[0];

            var reader = new FileReader();

            reader.onload = function (e) {

                var xml = e.target.result;

                callback(xml);
            };

            reader.readAsText(file);
        }

        function handleDragOver(e) {
            e.stopPropagation();
            e.preventDefault();

            e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
        }

        container.get(0).addEventListener('dragover', handleDragOver, false);
        container.get(0).addEventListener('drop', handleFileSelect, false);
    }

////// file drag / drop ///////////////////////

// check file api availability
    if (!window.FileList || !window.FileReader) {
        window.alert('Looks like you use an older browser that does not support drag and drop. ' + 'Try using Chrome, Firefox or the Internet Explorer > 10.');
    } else {
        registerFileDrop(container, openDiagram);
    }

// bootstrap diagram functions

    YUEOE_InitProcessPage = function (config) {
        /*$('#js-create-diagram').click(function (e) {
            e.stopPropagation();
            e.preventDefault();

            createNewDiagram();
        });*/


        $('#process-save').click(function (e) {
            e.stopPropagation();
            e.preventDefault();
            bpmnModeler.saveXML({ format: true }, function(err, xml) {
                var param = new FormData();
                param.append('tenant-id', "1-0001");
                param.append('enable-duplicate-filtering', true);
                param.append('deployment-source', 'process application');
                param.append('deployment-name', "test-m2.bpmn")
                param.append('file', new Blob([xml], { type: 'text/xml' }), "test-m2.bpmn");
                $.ajax({
                    url: '/rest/deployment/create',
                    type: 'post',
                    processData: false,
                    contentType: false,
                    data: param,
                    success: function () {
                        alert("ok")
                    }
                })
            });
        });
        var downloadLink = (0, _jquery2.default)('#js-download-diagram');
        var downloadSvgLink = (0, _jquery2.default)('#js-download-svg');

        $('.buttons a').click(function (e) {
            if (!$(this).is('.active')) {
                e.preventDefault();
                e.stopPropagation();
            }
        });

        function setEncoded(link, name, data) {
            var encodedData = encodeURIComponent(data);

            if (data) {
                link.addClass('active').attr({
                    'href': 'data:application/bpmn20-xml;charset=UTF-8,' + encodedData,
                    'download': name
                });
            } else {
                link.removeClass('active');
            }
        }

        var exportArtifacts = (0, _minDash.debounce)(function () {

            saveSVG(function (err, svg) {
                setEncoded(downloadSvgLink, 'diagram.svg', err ? null : svg);
            });

            saveDiagram(function (err, xml) {
                setEncoded(downloadLink, 'diagram.bpmn', err ? null : xml);
            });
        }, 500);

        bpmnModeler.on('commandStack.changed', exportArtifacts);
    };

};
